package gov.pbc.nn.kjgl.fxq.otherSources.view;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.exception.NoneLoginException;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;
import com.bstek.dorado.data.provider.Criteria;
import com.bstek.dorado.data.provider.Page;

import gov.pbc.nn.core.bdf.entity.Dept;
import gov.pbc.nn.core.dao.CommonHibernateDao;
import gov.pbc.nn.core.dao.PbcnnCoreJdbcDao;
import gov.pbc.nn.kjgl.fxq.attachment.AttachmentEntity;
import gov.pbc.nn.kjgl.fxq.organInfor.entity.OrganInfor;
import gov.pbc.nn.kjgl.fxq.otherSources.entity.OtherSourcesEntity;
import gov.pbc.nn.kjgl.fxq.otherSources.entity.SourcesOrgan;
import gov.pbc.nn.kjgl.fxq.workDocument.view.WorkDocumentPR;

@Component(OtherSourcesPR.BEAN_ID)
public class OtherSourcesPR extends CommonHibernateDao {
	public static final String BEAN_ID = "otherSourcesPR";

	@Resource(name = PbcnnCoreJdbcDao.BEAN_ID)
	private PbcnnCoreJdbcDao jdbcDao;

	@Resource(name = WorkDocumentPR.BEAN_ID)
	private WorkDocumentPR workDocumentPR;

	@DataProvider
	public List<OrganInfor> getAllOrgan() throws Exception {
		IUser user = ContextHolder.getLoginUser();
		if (user == null)
			throw new NoneLoginException("请先登录！");
		if (user.getDepts() == null || user.getDepts().isEmpty())
			throw new NoneLoginException("您未设置部门！");
		Dept dept = (Dept) user.getDepts().get(0);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("deptId", dept.getCDept().getId());
		return this.query("select o from OrganInfor o where o.deptId=:deptId and invalid=false", map);
	}

	@DataProvider
	public void loadAllOtherSources(Page<OtherSourcesEntity> page, Criteria criteria) throws Exception {
		IUser user = ContextHolder.getLoginUser();
		if (user == null)
			throw new NoneLoginException("请先登录！");
		if (user.getDepts() == null || user.getDepts().isEmpty())
			throw new NoneLoginException("您未设置部门！");
		Dept dept = (Dept) user.getDepts().get(0);
		List<String> childrenIds = this.workDocumentPR.getAllChildOrgDeptId(dept.getCDept().getParentId());
		// System.out.println(dept.getCDept().getName());
		childrenIds.add(dept.getCDept().getId());
		DetachedCriteria detachedCriteria = this.buildDetachedCriteria(criteria, OtherSourcesEntity.class);
		detachedCriteria.add(Restrictions.or(Restrictions.eq("createUser", user.getUsername()), Restrictions.and(Restrictions.in("deptId", childrenIds), Restrictions.eq("state", 20))));
		detachedCriteria.add(Restrictions.eq("invalid", false));
		if (criteria != null && criteria.getOrders() != null && !criteria.getOrders().isEmpty()) {
			com.bstek.dorado.data.provider.Order order = criteria.getOrders().get(0);
			if (order.isDesc()) {
				detachedCriteria.addOrder(Order.desc(order.getProperty()));
			} else {
				detachedCriteria.addOrder(Order.asc(order.getProperty()));
			}
		} else {
			detachedCriteria.addOrder(Order.desc("createDate"));
		}
		this.pagingQuery(page, detachedCriteria);
		
		Map<String, Object> map = new HashMap<String, Object>();
		String sql="select o from SourcesOrgan so,OrganInfor o where  so.sourcesId=:sourcesId and so.organId=o.id and so.invalid=false ";
		List<OtherSourcesEntity> entitys = new ArrayList<OtherSourcesEntity>();
		for (OtherSourcesEntity sources : page.getEntities()) {
			OtherSourcesEntity sourcesEntity = EntityUtils.toEntity(sources);
			map.put("sourcesId", sources.getId());			
			List<OrganInfor> organs = this.query(sql, map);
			EntityUtils.setValue(sourcesEntity, "organs", organs);
			String organName = "";
			String organCode = "";
			for (OrganInfor organInfor : organs) {
				organName += organInfor.getOrganName() + ",";
				organCode += organInfor.getOrganNum() + ",";
			}
			if (organName.length() > 0)
				organName = organName.substring(0, organName.length() - 1);
			EntityUtils.setValue(sourcesEntity, "organName", organName);
			if (organCode.length() > 0)
				organCode = organCode.substring(0, organCode.length() - 1);
			EntityUtils.setValue(sourcesEntity, "organCode", organCode);
			entitys.add(sourcesEntity);
		}
		page.setEntities(entitys);
	}

	@DataResolver
	@Transactional
	public void saveOtherSources(List<OtherSourcesEntity> otherSourcesEntities) throws Exception {
		IUser user = ContextHolder.getLoginUser();
		if (user == null)
			throw new NoneLoginException("请先登录！");
		if (user.getDepts() == null || user.getDepts().isEmpty())
			throw new NoneLoginException("您未设置部门！");
		Dept dept = (Dept) user.getDepts().get(0);
		for (OtherSourcesEntity otherSources : otherSourcesEntities) {
			EntityState state = EntityUtils.getState(otherSources);
			OtherSourcesEntity otherSourcesEntity = EntityUtils.toEntity(otherSources);
			otherSources.setState(10);
			if (state.equals(EntityState.NEW)) {
				otherSources.setDeptId(dept.getCDept().getId());
				otherSources.setDeptName(dept.getCDept().getName());
				this.save(otherSources);
			} else if (state.equals(EntityState.MODIFIED)) {
				this.update(otherSources);
			} else if (state.equals(EntityState.DELETED)) {
				this.delete(otherSources);
			}

			List<AttachmentEntity> attachments = EntityUtils.getValue(otherSourcesEntity, "attachments");
			if (attachments != null) {
				this.update(otherSources);
				for (AttachmentEntity attachmentEntity : attachments) {
					this.workDocumentPR.saveEntity(attachmentEntity);
				}
			}
			
			List<OrganInfor> organInfors = EntityUtils.getValue(otherSourcesEntity, "organs");
			if (organInfors != null) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("sourcesId", otherSources.getId());
				this.executeUpdate("update SourcesOrgan set invalid=true where sourcesId=:sourcesId ", map);
				for (OrganInfor organInfor : organInfors) {
					EntityState stateorgan = EntityUtils.getState(organInfor);
					if (!stateorgan.equals(EntityState.DELETED)) {
						SourcesOrgan so = new SourcesOrgan();
						so.setSourcesId(otherSources.getId());
						so.setOrganId(organInfor.getId());
						this.save(so);
					}
				}
			}
		}

	}

	@Expose
	@DataResolver
	@Transactional
	public void submitOtherSources(OtherSourcesEntity otherSources) throws Exception {
		if (otherSources.getState() != 20) {
			otherSources.setState(20);
			otherSources.setSubmitDate(new Date());
			this.update(otherSources);
		}
	}
}
